//
//  PayCouponViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/7/12.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit

class PayCouponViewController: UITableViewController {

    var money: String?
    var data = [Order.PayCoupon.Coupon]()
    
    weak var delegate: ReturnDetailViewController?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        guard let money = money else {
            return
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        Order.payCoupon(money: money, success: { [weak self] data in
            JZLoading.hideLoading()
            if let data = data, let self = self {
                self.data = data
                self.tableView.reloadData()
                if data.count == 0 {
                    UIView.showInfoViewWithEmpty(self.view, text: "暂无优惠券")
                }
            }
        }) { [weak self] error in
            JZLoading.hideLoading()
            self?.showError(error)
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        let item = data[indexPath.row]
        
        if let cell = cell as? PayCouponCell {
            cell.couponNameLabel.text = item.couponName
            cell.briefLabel.text = item.brief
            cell.briefLabel.sizeToFit()
            cell.expireTimeLabel.text = item.expireTime
        }

        return cell
    }

    // MARK: - Table view delegate
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let item = data[indexPath.row]
        delegate?.couponId = item.couponId
        
        navigationController?.popViewController(animated: true)
    }
}
